package control.face
{
	import core.Control;
	import core.Model;
	import core.View;
	
	import events.SitEvent;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	
	import global.Resource;
	
	import utils.DisplayTool;
	import utils.animate.TweenEmote;

	public class EmoteControl
	{
		private var _view:View = View.getInstance();
		private var _model:Model = Model.getInstance();
		private var _control:Control = Control.getInstance();
		private var tweens:Array;
		
		public function EmoteControl()
		{
			initListener();
			initTweens();
		}
		
		private function initTweens():void
		{
			tweens = [];
			for (var i:int=0; i<6; i++)
			{
				var tween:TweenEmote = new TweenEmote();
				tween.duration = 2.5;
				tween.addEventListener(Event.COMPLETE,onTweenEmoteComplete);
				tweens.push(tween);
			}
		}
		
		private function onTweenEmoteComplete(event:Event):void
		{
			removeTweenEmote(event.target as TweenEmote);
		}
		
		private function initListener():void
		{
			_model.sitModel.addEventListener(SitEvent.SIT_EMOTE,onEmote);
			_model.sitModel.addEventListener(SitEvent.REMOVE,onSitRemove);
		}
		
		private function onSitRemove(event:SitEvent):void
		{
			var sitId:int = event.sitData.id;
			var tween:TweenEmote = tweens[sitId];
			tween.stop();
			removeTweenEmote(tween);
			
		}
		
		private function removeTweenEmote(tween:TweenEmote):void
		{
			var emote:MovieClip = tween.target as MovieClip;
			if (emote)
			{
				emote.stop();
				
				if (emote.s != null)
				{
					emote.s.stop();
					emote.s = null;
				}
				
				DisplayTool.removeChild(emote.parent,emote);
			}
		}
		
		private function onEmote(event:SitEvent):void
		{
			var sitId:int = event.sitId;
			var emoteKey:String = event.emoteKey;
			var emote:MovieClip = Resource.getEmote(emoteKey);
			var tween:TweenEmote = tweens[sitId];
			removeTweenEmote(tween);
			tween.setTarget(emote,sitId);
			tween.start();
			_view.tableLayer.addEmote(emote);
			
			emote.s = _control.soundControl.playSound("s" + emoteKey);
			
		}
		
		public function clear():void
		{
			DisplayTool.removeAllChild(_view.tableLayer.emoteLayer);
			for each (var tween:TweenEmote in tweens)
			{
				tween.stop();
			}
		}
		
		public function open():void
		{
			_view.emotePanel.open();
		}
	}
}